package com.henry.utils;

import com.henry.constant.SecurityConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Liu Hanlin
 * @create 2025-02-17 23:26
 */
public class JwtUtil {

    // JWT的密钥（请保持密钥的安全）
    private static final String SECRET_KEY = "aGVsbG93b3JsZGhleWhvamFpbGhsdmVyZm9yZXZlcg==";

    // JWT的有效期 30 min
    private static final long EXPIRATION_TIME = 1000 * 60 * 30;

    /** 生成JWT Token的方法，参数为Map */
    public static String generateToken(Map<String, Object> claims) {
        long currentTimeMillis = System.currentTimeMillis();

        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date(currentTimeMillis))
                .setExpiration(new Date(currentTimeMillis + EXPIRATION_TIME))
                .signWith(Keys.hmacShaKeyFor(SECRET_KEY.getBytes()), SignatureAlgorithm.HS256)
                .compact();
    }

    /** 提取JWT Token中的用户id*/
    public static String extractUsername(String token) {
        return parseToken(token).get(SecurityConstants.USER_ID, String.class);
    }

    /** 提取JWT Token中的角色 */
    public static String extractRole(String token) {
        return parseToken(token).get(SecurityConstants.ROLE_CODE, String.class);
    }

    /** 提取JWT Token中的权限 */
    public static String[] extractPermissions(String token) {
        return parseToken(token).get("permissions", String[].class);
    }

    /** 提取JWT Token中的最后登录时间 */
    public static long extractLastLoginTime(String token) {
        return parseToken(token).get("lastLoginTime", Long.class);
    }

    /** 判断JWT是否已过期 */
    public static boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    /** 提取JWT的过期时间 */
    private static Date extractExpiration(String token) {
        return parseToken(token).getExpiration();
    }

    /** 验证JWT Token是否有效（用户名、过期时间检查等） */
    public static boolean validateToken(String token, String username) {
        String tokenUsername = extractUsername(token);
        return (username.equals(tokenUsername) && !isTokenExpired(token));
    }

    public static Claims parseToken(String token){
        return Jwts.parser()
                .setSigningKey(Keys.hmacShaKeyFor(SECRET_KEY.getBytes()))
                .parseClaimsJws(token)
                .getBody();
    }
    public static void main(String[] args) {
        // 创建测试载荷数据
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", "123456");
        claims.put("username", "testUser");
        claims.put("role", "ADMIN");

        // 生成Token
        String token1 = JwtUtil.generateToken(claims);
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoidXNlcklkIiwicm9sZV9jb2RlIjoicm9sZUNvZGUiLCJpYXQiOjE3NjAzNzQyOTYsImV4cCI6MTc2MDM3NjA5Nn0.Rynvy95GiuDUnJ4-VYuxEQhwR6Dot-4JXlXkUWtegTA";
        System.out.println("Generated Token: " + token);

        // 解析Token
        try {
            Claims parsedClaims = JwtUtil.parseToken(token);
            System.out.println("Parsed Claims: " + parsedClaims);

            // 提取特定信息
            String userId = JwtUtil.extractUsername(token);
            String role = JwtUtil.extractRole(token);
            System.out.println("User ID: " + userId);
            System.out.println("Role: " + role);

            // 验证Token有效性
            boolean isValid = JwtUtil.validateToken(token, "testUser");
            System.out.println("Token Valid: " + isValid);

            // 检查过期状态
            boolean isExpired = JwtUtil.isTokenExpired(token);
            System.out.println("Token Expired: " + isExpired);
        } catch (Exception e) {
            System.err.println("Error parsing token: " + e.getMessage());
        }
    }


}
